<template>
  <div class="cart-container">
    <!-- 左侧内容区域 -->
    <div class="cart-left">
      <!-- 标题和操作按钮 - 只在有商品时显示 -->
      <div class="cart-top-section" v-if="cartList.length > 0">
        <div class="cart-header">
          <h2>购物车({{ cartCount }})</h2>
        </div>
        <div class="cart-actions">
          <el-checkbox v-model="selectAll" @change="handleSelectAll">全选</el-checkbox>
          <el-button type="text" @click="handleClearCart">清空购物车</el-button>
          <el-button type="text" @click="handleDeleteSelected" :disabled="selectedCount === 0">删除选中</el-button>
        </div>
        <hr class="cart-separator">
      </div>
      <!-- 商品列表 -->
      <div class="cart-items">
        <!-- 空购物车状态 - 居中显示 -->
        <div v-if="cartList.length === 0 && !loading" class="empty-cart-wrapper">
          <div class="empty-cart">
            <el-empty description="购物车空空如也~"></el-empty>
            <el-button type="primary" @click="$router.push('/')">去逛逛</el-button>
          </div>
        </div>
        <!-- 加载状态 -->
        <div v-if="loading" class="loading-wrapper">
          <el-skeleton :rows="5" animated />
        </div>
        <!-- 商品列表 -->
        <div class="cart-item" v-for="item in cartList" :key="item.cartId" v-else-if="!loading">
          <el-checkbox v-model="item.checked" @change="handleItemCheckChange(item)"></el-checkbox>
          <div class="item-info-container">
            <div class="item-image">
              <el-image :src="item.mainImage || ''" fit="cover" @click="goToProductDetail(item.productId)"></el-image>
            </div>
            <div class="item-info">
              <div class="item-title" @click="goToProductDetail(item.productId)">{{ item.productName }}</div>
              <div class="item-specs">
                <span class="spec" v-if="item.brand">{{ item.brand }}</span>
              </div>
              <div class="item-price">￥{{ item.price.toFixed(2) }}</div>
            </div>
          </div>
          <div class="item-quantity-container">
            <el-input-number
                v-model="item.quantity"
                :min="1"
                :max="item.stock"
                size="small"
                @change="handleQuantityChange(item)"
            ></el-input-number>
            <div class="stock-info">
              剩余库存:
              <span :class="item.stock < 10 && item.stock > 0 ? 'low-stock' : item.stock <= 0 ? 'out-of-stock' : ''">
                {{ item.stock }}
              </span>
              <span v-if="item.stock < 10 && item.stock > 0" class="stock-tip">(库存紧张)</span>
              <span v-if="item.stock <= 0" class="out-of-stock">(已售罄)</span>
            </div>
          </div>
          <el-button type="danger" size="small" :icon="Delete" circle @click="handleDeleteItem(item)" class="item-delete" />
        </div>
      </div>
    </div>

    <!-- 右侧结算框 - 只在有商品时显示 -->
    <div class="cart-summary" v-if="cartList.length > 0 && !loading">
      <div class="summary-header">结算信息</div>
      <div class="summary-row">
        <span>商品总数</span>
        <span>{{ selectedCount }}件</span>
      </div>
      <div class="summary-row">
        <span>商品总价</span>
        <span>¥{{ totalPrice }}</span>
      </div>
      <div class="summary-total">
        <span class="total-label">应付总额：</span>
        <span class="total-price">¥{{ totalPrice }}</span>
      </div>
      <el-button type="primary" class="checkout-btn" :disabled="selectedCount === 0" @click="handleCheckout">
        去结算({{ selectedCount }})
      </el-button>
      <!-- 下单弹窗表单 -->
      <el-dialog v-model="orderDialogVisible" title="填写收货信息" width="400px">
        <el-form :model="orderForm" :rules="orderFormRules" ref="orderFormRef" label-width="80px">
          <el-form-item label="收货人" prop="receiverName">
            <el-input v-model="orderForm.receiverName" />
          </el-form-item>
          <el-form-item label="手机号" prop="receiverPhone">
            <el-input v-model="orderForm.receiverPhone" />
          </el-form-item>
          <el-form-item label="收货地址" prop="receiverAddress">
            <el-input v-model="orderForm.receiverAddress" />
          </el-form-item>
          <el-form-item label="备注">
            <el-input v-model="orderForm.remark" />
          </el-form-item>
        </el-form>
        <template #footer>
          <el-button @click="orderDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitOrder">提交订单</el-button>
        </template>
      </el-dialog>
    </div>
  </div>
</template>

<script setup>

import { ref, computed, onMounted } from 'vue';
import { useRouter } from 'vue-router';
import { ElMessage, ElMessageBox } from 'element-plus';
import { Delete } from '@element-plus/icons-vue';
import { createOrder } from '../api/order';
// 引入 API 方法，需确保 @/api/cart 路径正确
import {
  getCartList,
  updateCartQuantity,
  removeFromCart as deleteCartItem,
  batchRemoveFromCart,
  clearCart,
  getCheckedCartItems,
  updateCartChecked,
  batchSelectCart
} from '@/api/cart';

const router = useRouter();
const cartList = ref([]);     // 购物车商品列表
const selectAll = ref(false); // 全选状态
const loading = ref(true);    // 加载状态
const cartCount = ref(0);     // 购物车商品总个数（接口返回的总数）

// 下单弹窗相关
const orderDialogVisible = ref(false)
const orderForm = ref({
  receiverName: '',
  receiverPhone: '',
  receiverAddress: '',
  remark: ''
})
const orderFormRules = {
  receiverName: [{ required: true, message: '请输入收货人姓名', trigger: 'blur' }],
  receiverPhone: [{ required: true, message: '请输入手机号', trigger: 'blur' }],
  receiverAddress: [{ required: true, message: '请输入收货地址', trigger: 'blur' }]
}
const orderFormRef = ref(null)

// 计算选中商品的数量总和（用于结算的商品总数）
const selectedCount = computed(() => {
  return cartList.value.reduce((total, item) => {
    return item.checked ? total + item.quantity : total;
  }, 0);
});

// 计算选中商品的总价
const totalPrice = computed(() => {
  return cartList.value
      .filter(item => item.checked)
      .reduce((sum, item) => sum + (item.price * item.quantity), 0)
      .toFixed(2);
});

// 获取购物车列表
const fetchCartList = async () => {
  try {
    loading.value = true;
    const res = await getCartList();
    console.log('购物车接口响应:', res);

    if (res.code === 0 && Array.isArray(res.data.cartItems)) {
      const formattedItems = res.data.cartItems.map(cartItem => {
        return {
          cartId: cartItem.id,
          userId: cartItem.userId,
          productId: cartItem.productId,
          productName: cartItem.productName,
          mainImage: cartItem.productImage,
          brand: cartItem.brand || '',
          price: cartItem.productPrice,
          stock: cartItem.stock || 0,
          originalStock: cartItem.stock || 0, // 保存原始库存
          images: cartItem.images || [],
          quantity: cartItem.quantity || 1,
          checked: cartItem.checked || false,
          createTime: cartItem.createTime,
          updateTime: cartItem.updateTime
        };
      });
      cartList.value = formattedItems;
      cartCount.value = res.data.totalCount || 0; // 接口返回的商品总个数
      // 同步全选状态
      selectAll.value = cartList.value.length > 0 && cartList.value.every(item => item.checked);
    } else {
      cartList.value = [];
      cartCount.value = 0;
      selectAll.value = false;
      ElMessage.warning(res.message || '购物车数据格式不正确');
    }
  } catch (error) {
    ElMessage.error('获取购物车数据失败');
    console.error('获取购物车数据失败:', error);
    cartList.value = [];
    cartCount.value = 0;
    selectAll.value = false;
  } finally {
    loading.value = false;
  }
};

// 全选/取消全选
const handleSelectAll = async (val) => {
  try {
    const cartIds = cartList.value.map(item => item.cartId);
    await batchSelectCart({ cartIds, checked: val });
    cartList.value.forEach(item => {
      item.checked = val;
    });
    ElMessage.success(val ? '已全选所有商品' : '已取消全选');
  } catch (error) {
    ElMessage.error('操作失败');
    console.error('批量选择购物车商品失败:', error);
  }
};

// 单个商品选中状态变化
const handleItemCheckChange = async (item) => {
  try {
    await updateCartChecked({ cartId: item.cartId, checked: item.checked });
    // 重新计算全选状态
    selectAll.value = cartList.value.every(i => i.checked);
  } catch (error) {
    ElMessage.error('更新选中状态失败');
    console.error('更新购物车商品选中状态失败:', error);
    // 回滚选中状态
    item.checked = !item.checked;
  }
};

// 数量变化
const handleQuantityChange = async (item) => {
  // 本地先更新库存显示
  updateLocalStock(item);

  try {
    const res = await updateCartQuantity({
      cartId: item.cartId,
      quantity: item.quantity
    });

    if (res.code === 0) {
      ElMessage.success(`已更新数量: ${item.quantity}`);
    } else {
      ElMessage.error('更新数量失败');
      // 回滚本地库存和数量
      item.quantity = item.quantity - 1;
      updateLocalStock(item);
    }
  } catch (error) {
    ElMessage.error('更新数量失败');
    console.error('更新购物车商品数量失败:', error);
    // 回滚本地库存和数量
    item.quantity = item.quantity - 1;
    updateLocalStock(item);
  }
};

// 更新本地库存显示
const updateLocalStock = (item) => {
  // 库存 = 原始库存 - (当前数量 - 1)
  item.stock = Math.max(0, item.originalStock - (item.quantity - 1));

  // 同步更新输入框最大数量限制（通过 CSS 选择器定位）
  const inputNumber = document.querySelector(`.cart-item[cart-id="${item.cartId}"] .el-input-number__input`);
  if (inputNumber) {
    inputNumber.max = item.stock;
  }
};

// 删除单个商品
const handleDeleteItem = async (item) => {
  try {
    await ElMessageBox.confirm('确定要删除该商品吗?', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    });

    const res = await deleteCartItem(item.cartId);
    if (res.code === 0) {
      cartList.value = cartList.value.filter(i => i.cartId !== item.cartId);
      cartCount.value = cartList.value.length;
      ElMessage.success('删除商品成功');
    } else {
      ElMessage.error('删除商品失败');
    }
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('删除商品失败');
      console.error('删除购物车商品失败:', error);
    }
  }
};

// 删除选中
const handleDeleteSelected = async () => {
  const selectedItems = cartList.value.filter(item => item.checked);
  if (selectedItems.length === 0) return;

  try {
    await ElMessageBox.confirm(`确定要删除选中的${selectedItems.length}件商品吗?`, '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    });

    const cartIds = selectedItems.map(item => item.cartId);
    const res = await batchRemoveFromCart(cartIds);

    if (res.code === 0) {
      cartList.value = cartList.value.filter(item => !item.checked);
      cartCount.value = cartList.value.length;
      ElMessage.success('删除成功');
    } else {
      ElMessage.error('删除失败');
    }
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('删除失败');
      console.error('批量删除购物车商品失败:', error);
    }
  }
};

// 清空购物车
const handleClearCart = async () => {
  try {
    await ElMessageBox.confirm('确定要清空购物车吗?', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    });

    const res = await clearCart();
    if (res.code === 0) {
      cartList.value = [];
      cartCount.value = 0;
      ElMessage.success('购物车已清空');
    } else {
      ElMessage.error('清空购物车失败');
    }
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('清空购物车失败');
      console.error('清空购物车失败:', error);
    }
  }
};

// 跳转到商品详情
const goToProductDetail = (productId) => {
  router.push(`/product/${productId}`);
};

// 结算功能 - 弹窗收集收货人信息
const handleCheckout = () => {
  if (selectedCount.value === 0) return
  orderDialogVisible.value = true
};

// 提交订单
const submitOrder = async () => {
  await orderFormRef.value.validate()
  const cartIds = cartList.value.filter(i => i.checked).map(i => i.cartId)
  try {
    await createOrder({
      cartIds,
      ...orderForm.value
    })
    ElMessage.success('订单创建成功，正在跳转订单页')
    orderDialogVisible.value = false
    router.push('/orders')
  } catch (e) {
    ElMessage.error('下单失败')
  }
};

// 组件挂载时获取购物车数据
onMounted(() => {
  fetchCartList();
});
</script>

<style>
.cart-container {
  max-width: 1200px;
  margin: 0 auto;
  padding: 20px;
  display: flex;
  gap: 20px;
  min-height: calc(100vh - 100px);
  position: relative;
}

/* 左侧区域 */
.cart-left {
  width: calc(100% - 360px);
  display: flex;
  flex-direction: column;
  gap: 5px;
}

.cart-top-section {
  background: transparent;
  padding: 10px 20px;
  border-radius: 8px;
  box-shadow: none;
}

.cart-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 15px;
}

.cart-header h2 {
  margin: 0;
  font-size: 20px;
  color: #333;
}

.cart-actions {
  display: flex;
  align-items: center;
  gap: 20px;
}

.cart-separator {
  border: none;
  border-top: 1px solid #e4e7ed;
  margin: 10px 0 5px 0;
}

/* 商品列表 */
.cart-items {
  background: transparent;
  padding: 0 20px;
  border-radius: 8px;
  box-shadow: none;
  flex: 1;
}

/* 修改后的商品项布局 */
.cart-item {
  display: flex;
  padding: 15px 0;
  align-items: flex-start; /* 顶部对齐 */
  border-bottom: 1px solid #f5f5f5;
  position: relative;
}

.cart-item:last-child {
  border-bottom: none;
}

.item-info-container {
  display: flex;
  align-items: flex-start; /* 顶部对齐 */
  flex: 1;
  margin-left: 15px;
}

.item-image {
  width: 80px;
  height: 80px;
  margin-right: 15px;
  flex-shrink: 0;
}

.item-image .el-image {
  width: 100%;
  height: 100%;
  border-radius: 4px;
  object-fit: cover;
  border: 1px solid #f0f0f0;
}

.item-info {
  flex: 1;
  min-width: 0;
}

.item-title {
  font-size: 16px;
  color: #333;
  margin-bottom: 8px;
  font-weight: 500;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

.item-specs {
  font-size: 13px;
  color: #999;
  margin-bottom: 8px;
}

.item-price {
  font-size: 18px;
  color: #f56c6c;
  font-weight: bold;
}

/* 重构后的数量控制区域 */
.item-quantity-section {
  display: flex;
  align-items: center;
  margin: 0 20px;
  min-height: 80px; /* 与图片同高 */
}

.item-quantity-container {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  height: 100%;
}

.item-quantity {
  margin: 0;
}

/* 修正后的库存信息样式 */
.stock-info {
  font-size: 12px;
  color: #999;
  white-space: nowrap;
  margin-top: 5px;
  height: 16px; /* 固定高度 */
  display: block;
  text-align: center;
}

.item-delete {
  margin-left: 20px;
  align-self: center; /* 垂直居中 */
  align-self: flex-start; /* 改为顶部对齐 */
}

/* 加载失败状态 */
.item-loading-failed {
  color: #f56c6c;
  font-size: 12px;
  margin-top: 5px;
  height: 16px; /* 与库存信息同高 */
}

/* 右侧结算框 */
.cart-summary {
  width: 300px;
  background-color: #fff;
  padding: 20px;
  border-radius: 10px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
  position: fixed;
  top: 200px;
  right: calc(50% - 600px + 20px);
  z-index: 10;
}

.summary-header {
  font-size: 18px;
  font-weight: 600;
  color: #333;
  padding-bottom: 15px;
  border-bottom: 1px solid #f0f0f0;
  margin-bottom: 15px;
}

.summary-row {
  display: flex;
  justify-content: space-between;
  margin-bottom: 12px;
  font-size: 14px;
  color: #666;
}

.summary-total {
  display: flex;
  justify-content: space-between;
  margin: 20px 0;
  padding-top: 15px;
  border-top: 1px solid #f0f0f0;
  font-size: 16px;
}

.total-price {
  color: #f56c6c;
  font-weight: bold;
  font-size: 20px;
}

.checkout-btn {
  width: 100%;
  height: 50px;
  font-size: 16px;
  margin-top: 10px;
  border-radius: 10px;
  background-color: #f56c6c;
  border-color: #f56c6c;
}

.checkout-btn:hover {
  background-color: #e05b5b;
  border-color: #e05b5b;
}

.checkout-btn.is-disabled {
  background-color: #f56c6c;
  border-color: #f56c6c;
  opacity: 0.6;
}

/* 空购物车样式 - 确保居中显示 */
.empty-cart-wrapper {
  display: flex;
  justify-content: center;
  align-items: center;
  width: 100%;
  height: 50%; /* 占满整个父容器高度 */
  position: absolute; /* 绝对定位 */
  top: 0;
  left: 0;
}

.empty-cart {
  text-align: center;
  padding: 20px;
  max-width: 400px;
  margin: 0 auto;
}

.empty-cart .el-button {
  margin-top: 20px;
  padding: 12px 24px;
}

/* 新增库存警告样式 */
.stock-warning {
  color: #f56c6c;
  font-size: 12px;
  margin-left: 5px;
}

/* 加载状态样式 */
.cart-item {
  transition: all 0.3s;
}

</style>